/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.util;

import java.math.BigInteger;

import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.constants.AsciiConstants;

/**
 * 长整型相关工具类
 *
 * @version v1.0.0 @author zouzhigang 2014-2-27 新建与整理
 */
@AnAlias("Longs")
public class Longs implements AsciiConstants
{
    /** 字符串转换为int,异常不处理 注:默认10进制 */
    public static long toLong(String s)
    {
        return Long.parseLong(s);
    }

    /** 字符串转换为int 如果异常则返回异常值 */
    public static long toLong(String s, long defaultValue)
    {
        try{return Long.parseLong(s);}catch(NumberFormatException e){return defaultValue;}
    }
    
    /** 对象转换为int 如果异常则返回异常值 */
    public static long toLong(Object o, long defaultValue)
    {
        if (o == null)
            return defaultValue;
        else if (o instanceof Integer)
            return (Integer)o;
        else if (o instanceof Long)
            return (Long)o;
        else if (o instanceof String)
            return toLong((String)o, defaultValue);
        else
            return defaultValue;
    }
    
    public static int length(long val)
    {
        if (val == 0)
            return 1;
        
        boolean isNegative = false; 
        if (val < 0)
        {//负数变为正数
            val = -val;
            isNegative = true;
        }
        
        int len = 0;
        for (long i=val;i!=0;i/=10)
        {//对值作10的整除
            len++;
        }
        
        return isNegative?len+1:len;
    }
    
    public static long getMaxLong(int length)
    {
        if (length >= 19)
            return 0x7FFFFFFFFFFFFFFFL;
        
        if (length <= 0)
            return 9;
        
        String maxString = "999999999999999999".substring(0, length);
        return toLong(maxString);
    }
    
    public static int compareUnsigned(long a, long b)
    {//先去掉符号位比，相等再比符号位
        long cmp = (a >>> 1) - (b >>> 1);
        if (cmp != 0)
            return cmp>0?1:-1;
        
        cmp = ((a & 1) - (b & 1));
        return cmp>0?1:(cmp<0?-1:0);
    }
    
    public static String toHexString(long val)
    {
        return Long.toHexString(val);
    }
    
    public static long toHexLong(String val)
    {//小于0-7开头的为正长整型，使用Long.parseLong即可，8-F开头的为负长整型需要转为BigInteger，性能差3倍
        return (val.charAt(0) < _8_)?Long.parseLong(val, 16):new BigInteger(val, 16).longValue();
    }
}
